package com.jxd.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.jxd.constant.JwtClaimsConstant;
import com.jxd.context.BaseContext;
import com.jxd.user.domain.dto.UsersDto;
import com.jxd.user.domain.pojo.Role;
import com.jxd.user.domain.pojo.Users;
import com.jxd.user.domain.utils.Result;
import com.jxd.user.mapper.RoleMapper;
import com.jxd.user.mapper.UsersMapper;
import com.jxd.user.properties.JwtProperties;
import com.jxd.user.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxd.utils.AppJwtUtil;
import com.jxd.utils.JwtUtil;
import com.jxd.utils.MD5Util;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-06-06
 */
@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
@Autowired
    private RoleMapper roleMapper;
/*
* 登录*/
    @Autowired
    private JwtProperties jwtProperties;
@Override
    public Result load(UsersDto dto) {
    String password = dto.getPassword();
    //md5加密
    dto.setPassword( MD5Util.md5(password));
    log.info("用户登录：{}", dto);
    // 查询用户
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getUsername, dto.getUsername())
                .eq(Users::getPassword, dto.getPassword());
        Users users = getOne(wrapper);
        log.info("用户登录：{}", users);
        if (users == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 查询角色
        Role role = roleMapper.selectById(users.getRoleId());
        if (role == null){
            throw new RuntimeException("没有权限");
        }
            HashMap<String, Object>  claims= new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID, users.getId());
            claims.put(JwtClaimsConstant.PERMISSSION,role.getPermission());
            String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(),claims );
            return Result.success(token);
    }

    @Override
    public Result save(UsersDto dto) {
        checkPermission();
        //新增
        Users users = new Users();
        BeanUtils.copyProperties(dto,users);
        save(users);
        return Result.success();
    }

    @Override
    public Result compile(UsersDto dto) {
        checkPermission();
        Users users = getById(dto.getId());
        if (users == null){
            throw new RuntimeException("用户不存在");
        }
         BeanUtils.copyProperties(dto,users);
        boolean booolean = save(users);
        if (booolean){
            return Result.success();
        }else {
            return Result.error("修改失败");
        }
    }

    @Override
    public Result removeByuser(Integer id) {
        checkPermission();
        boolean booolean = removeById(id);
        if (booolean){
            return Result.success();
        }else {
            return Result.error("删除失败");
        }
    }

    @Override
    public Result selectByID(Integer id) {
        checkPermission();
        Users users = getById(id);
        if (users == null){
            throw new RuntimeException("用户不存在");
        }
        return Result.success(users);
    }

    //校验权限
    private void checkPermission() {
        //从线程中取出用户id
        Long currentId = BaseContext.getCurrentId();
        Users user = getById(currentId);
        Role role = roleMapper.selectById(user.getRoleId());
        if (!role.getPermission().equals("1")){
            throw new RuntimeException("没有权限");
        }
    }

}
